<template>
  <div>
    <el-button type="primary" @click="type = ShowType.Route" :disabled="type == ShowType.Route">路由表</el-button>
    <el-button type="primary" @click="type = ShowType.Broad" :disabled="type == ShowType.Broad">广播路由</el-button>
    <el-button type="primary" @click="getRouteTable">刷新</el-button>
    <el-button type="primary" @click="showChangeRoute(null)">新增</el-button>
    <div style="margin-top: 20px">
      <el-table :data="type == ShowType.Broad ? routeBroadcast : route" border v-loading="loading">
        <el-table-column prop="destination" label="目标" />
        <el-table-column prop="mask" label="mask" />
        <el-table-column prop="gateway" label="网关" />
        <el-table-column prop="metric" label="跃点数" />
        <el-table-column prop="ip" label="网卡" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="deleteRoute(scope.row)">删除</el-button>
            <el-button type="primary" size="small" @click="showChangeRoute(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :modal="false">
    <el-form  label-width="auto">
      <el-form-item label="目标">
        <el-input  v-model="form.destination"></el-input>
      </el-form-item>
      <el-form-item label="mask">
        <el-input  v-model="form.mask"></el-input>
      </el-form-item>
      <el-form-item label="网关">
        <el-input  v-model="form.gateway"></el-input>
      </el-form-item>
      <el-form-item label="跃点数">
        <el-input  v-model="form.metric"></el-input>
      </el-form-item>
      <el-form-item label="网卡">
        <el-select v-model="form.ifIndex" placeholder="选择网卡">
          <el-option
            v-for="item in netList"
            :key="item.ifIndex"
            :label="item.name + '-' + item.ipv4"
            :value="item.ifIndex"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changeRoute"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, toRaw } from 'vue'
import type { RouteConf } from 'main/types/interfaces'
import { netList } from '@/global/store'
enum ShowType {
  Route = 1,
  Broad = 2,
}

const type = ref(ShowType.Broad)
const loading = ref(false)
onMounted(() => {
  getRouteTable()
})

const route = ref<RouteConf[]>([])
const routeBroadcast = ref<RouteConf[]>([])
const getRouteTable = async () => {
  loading.value = true
  route.value = await window.electron.showRouteTable()
  routeBroadcast.value = []
  console.log(route.value)
  route.value.map((v: RouteConf) => {
    if (v.destination == '255.255.255.255' || v.destination == '224.0.0.0') {
      routeBroadcast.value.push(v)
    }
  })
  loading.value = false
}

const deleteRoute = async (data: RouteConf) => {
  // 获取原始对象
  const raw = toRaw(data)
  console.log('删除路由', raw)
  try {
    await window.electron.deleteRoute(raw)
  } catch (e) {
    console.error('删除路由:', e)
    ElMessage.error('删除路由' + e)
  }
}

const getNetIfIpById = (id: string): string => {
  for (const network of netList.value) {
    if (network.ifIndex == id) return network.ipv4
  }
  return ''
}

const dialogVisible = ref(false)
const form = ref<RouteConf>({destination: "", gateway: "", ip: "", mask: "", metric: "", ifIndex: "",})

const showChangeRoute = (conf: RouteConf|null) => {
  form.value = { ifIndex: "", destination: "", gateway: "", ip: "", mask: "", metric: "" }
  if (conf) {
    const original = toRaw(conf)
    form.value = JSON.parse(JSON.stringify(original))
    if (form.value.gateway == "在链路上") {
      form.value.gateway = form.value.ip
    }
  }
  dialogVisible.value = true
}

const changeRoute = async () => {
  form.value.ip = getNetIfIpById(form.value.ifIndex)
  const info = `${form.value.destination}${form.value.mask}${form.value.gateway}${form.value.ip}`
  let type = 'add'
  for (const network of route.value) {
    const infov = `${network.destination}${network.mask}${network.gateway=="在链路上"?network.ip:network.gateway}${network.ip}`
    if (info == infov) {
      type = "change"
      break
    }
  }

  try {
    await window.electron.changeRoute(type, toRaw(form.value))
    ElMessage.success("成功")
    dialogVisible.value = false
    getRouteTable()
  } catch (e) {
    console.error(e)
    if (String(e).indexOf("操作完成!") > -1) {
      ElMessage.success("成功")
      dialogVisible.value = false
      getRouteTable()
      return
    }
    ElMessage.error((type == "add" ? "添加" :"修改" ) + '路由' + e)
  }

}
</script>
